const path = require('path')
const fs = require('fs')
const utils = require('./src/lib/utils')
const pkg = require('./package.json')

const appDirectory = fs.realpathSync(process.cwd())
const env = process.env.NODE_ENV
// eslint-disable-next-line no-console
console.info(`当前执行环境${env}`)

module.exports = {
  publicPath: '/vue3-app',
  outputDir: 'dist',
  assetsDir: 'static',
  pages: utils.getEntry(`${appDirectory}/src/pages/*/*.js`),

  configureWebpack: {
    resolve: {
      alias: {
        '@': './src/pages',
        vue$: 'vue/dist/vue.runtime.esm.js',
      },
    },
    plugins: [
      function () {
        // 数据处理 用于生成 webpackMap
        this.plugin('done', (map) => {
          let webpackMap = {}
          // 调用 webpack map toJson 生成 jsonMap
          map = map.toJson()
          Object.keys(map.entrypoints).forEach((item) => {
            // 页面名
            let pageName = item
            webpackMap[pageName] = {}
            webpackMap[pageName].js = []
            webpackMap[pageName].css = [];

            // 公共资源 (映射) 处理
            [].concat(map.assetsByChunkName['chunk-vendors']).forEach(mapAsset);
            [].concat(map.assetsByChunkName['chunk-common']).forEach(mapAsset);
            // 页面级别资源 (映射) 处理
            [].concat(map.assetsByChunkName[item]).forEach(mapAsset)

            /**
             * 根据资源类型，将其映射(map)到对应的数组中
             * @param assetsPath  资源路径
             */
            function mapAsset(assetsPath) {
              if (!assetsPath) {
                return
              }

              if (path.extname(assetsPath) === '.js') {
                // 绝对路径 = publicPath +  assetsPath
                webpackMap[pageName].js.push(map.publicPath + assetsPath)
              } else if (path.extname(assetsPath) === '.css') {
                webpackMap[pageName].css.push(map.publicPath + assetsPath)
              }
            }
          })

          // webpackMap 写入 config.json
          require('fs').writeFileSync(
            path.join(__dirname, 'resource.map.json'),
            JSON.stringify(webpackMap, null, '  '),
          )
        })
      },
    ],
  },

  chainWebpack: config => {
    const types = ['vue-modules', 'vue']
    types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))

    function addStyleResource(rule) {
      rule.use('style-resource')
        .loader('style-resources-loader')
        .options({
          patterns: [
            path.resolve(__dirname, './src/assets/common.less'), // 需要全局导入的less
          ],
        })
    }
  },

  devServer: {
    port: 8888, // 端口
    disableHostCheck: true,
  },
}
